<?php

namespace App\Http\Controllers\Steel;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Chanjet\TplusCommonController;
use App\Http\Validate\Steel\SteelType as SteelSteelType;
use App\Jobs\Inventory;
use App\Models\Steel\SteelArchive;
use App\Models\Steel\SteelType;
use App\Services\Chanjet\ChanjetRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;
use App\Services\Common\CommonExcelExport;
/**
 * 钢材分类相关
 */
class SteelTypeController extends BaseController
{
    /**
     * 获取列表
     */
    public function getlist(Request $request)
    {
        //需获取当前用户所属账套
        $status = $request->status ?? 0;
        $isgetall = $request->isgetall ?? 0;
        $list = SteelType::getList($request, $this->mangerinfo['cpid'], $status, $isgetall);
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }

    /**
     * 新增分类
     */
    public function dopostadd(Request $request)
    {
        $req_data = $request->only(['type_no', 'type_name']);

        $Validate = new SteelSteelType();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $isexist = SteelType::where([['cpid', $this->mangerinfo['cpid']], ['type_no', $req_data['type_no']]])
            ->orWhere([['cpid', $this->mangerinfo['cpid']], ['type_name', $req_data['type_name']]])->first();

        if ($isexist) {
            return response()->json(['code' => '001', 'msg' => '钢材分类编码、钢材分类名称不允许重复']);
        }

        $data = [
            'cpid' => $this->mangerinfo['cpid'],
            'type_no' => $req_data['type_no'],
            'type_name' => $req_data['type_name'],
            'update_at' => time()
        ];
        $data['create_at'] = time();
        SteelType::create($data)->id;

        /**
         *   新增存货分类
         *
         */
        $requestData = [
            "api" => "inventoryClassCreate",
            "param" => ["dto" => ["Code" => $req_data["type_no"], "Name" => $req_data["type_name"]]],
            "mangerinfo" => $this->mangerinfo
        ];
        Inventory::dispatch($requestData);
//        $start_block = microtime(true);
//        if (TplusCommonController::isAllowRequestTplus($this->mangerinfo)) {
//            ChanjetRequest::getInstance()->inventoryClassCreate(["dto" => ["Code" => $req_data["type_no"], "Name" => $req_data["type_name"]]], $this->mangerinfo['org_id']);
//        }
//        $time_block = microtime(true)- $start_block;
//        Log::info("同步存货信息,time: ".$time_block);



        return response()->json(['code' => '000', 'msg' => '新增成功']);
    }

    /**
     * 新增二级分类
     */
    public function dopostaddsub(Request $request)
    {
        $req_data = $request->only(['pid', 'type_no', 'type_name']);


        $Validate = new SteelSteelType('addsub');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $info = SteelType::where([['id', $req_data['pid']], ['cpid', $this->mangerinfo['cpid']]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '父级分类参数错误']);
        }

        $isexist = SteelType::where([['cpid', $this->mangerinfo['cpid']], ['type_no', $req_data['type_no']]])->orWhere([['cpid', $this->mangerinfo['cpid']], ['type_name', $req_data['type_name']]])->first();

        if ($isexist) {
            return response()->json(['code' => '001', 'msg' => '钢材分类编码、钢材分类名称不允许重复']);
        }

        $data = [
            'cpid' => $this->mangerinfo['cpid'],
            'pid' => $info['id'],
            'type_no' => $req_data['type_no'],
            'type_name' => $req_data['type_name'],
            'update_at' => time()
        ];
        $data['create_at'] = time();
        SteelType::create($data)->id;
        /**
         *
         *  新增存货子分类
         *
         */
//        if (TplusCommonController::isAllowRequestTplus($this->mangerinfo)) {
//            ChanjetRequest::getInstance()->inventoryClassCreate([
//                "dto" => [
//                    "Code" => $req_data['type_no'],
//                    "Name" => $req_data["type_name"],
//                    "Parent" => ["Code" => $info["type_no"], "Name" => $info["type_name"]],
//                ]
//            ], $this->mangerinfo['org_id']);
//        }

        $requestData = [
            "api" => "inventoryClassCreate",
            "param" => [
                "dto" => [
                    "Code" => $req_data['type_no'],
                    "Name" => $req_data["type_name"],
                    "Parent" => ["Code" => $info["type_no"], "Name" => $info["type_name"]],
                ]
            ],
            "mangerinfo" => $this->mangerinfo
        ];
        Inventory::dispatch($requestData);

        return response()->json(['code' => '000', 'msg' => '新增成功']);
    }

    /**
     * 冻结
     */
    public function changestatus(Request $request)
    {

        $id = $request->id ?? 0;
        $info = SteelType::where([['id', $id], ['cpid', $this->mangerinfo['cpid']]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $status = 2;
        SteelType::where([['id', $id]])->update(['status' => $status, 'update_at' => time()]);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }



    public function doexport(Request $request)
    {
        $list = SteelType::getList($request, $this->mangerinfo['cpid'],0, 0);



        $exceldata = [];
        $row = [
            [
                'type_no' => '钢材分类',
                'type_name' => '分类名称',
                'subtype_no' => '子分类编码',
                'subtype_name' => '子分类名称',
            ]
        ];
        foreach ($list['list'] as $key => $val) {
            $row[]=[
                'type_no' => $val['type_no'],
                'type_name' => $val['type_name'],
                'subtype_no' => '',
                'subtype_name' => '',
            ];

            foreach($val['subtype'] as $k=>$v){
                $row[]=[
                    'type_no' => $val['type_no'],
                    'type_name' => $val['type_name'],
                    'subtype_no' => $v['type_no'],
                    'subtype_name' => $v['type_name'],
                ];
            }

        }

        $datawith = [];
        $filename = '钢材分类导出.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata, $datawith), $filename);
    }


    /**
     * 删除
     */
    public function dodel(Request $request)
    {

        $id = $request->id ?? 0;
        $info = SteelType::where([['id', $id], ['cpid', $this->mangerinfo['cpid']]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        //查询此钢材分类是否已经被使用；钢材档案和钢材子分类都不能使用；
        $isexist = SteelArchive::where('type_id','=',$id)->first();
        if($isexist){
            return response()->json(['code' => '001', 'msg' => '此分类已有钢材档案使用，不能删除']);
        }
        // 检查是否有子分类被其他档案使用
        $subTypes = SteelType::where('pid','=',$id)->get();
        foreach ($subTypes as $subType) {
            $isSubTypeUsed = SteelArchive::where('type_id','=',$subType->id)->first();
            if($isSubTypeUsed){
                return response()->json(['code' => '001', 'msg' => '该分类的子分类已被钢材档案使用，不能删除']);
            }
        }
        DB::beginTransaction();
        try {
            SteelType::where('pid','=',$id)->delete();
            $res = SteelType::where([['id', $id]])->delete();
            if ($res) {
                DB::commit();
                return response()->json(['code' => '000', 'msg' => '操作成功']);
            } else {
                DB::rollBack();
                return response()->json(['code' => '001', 'msg' => '操作失败']);
            }
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '删除失败：' . $e->getMessage()]);
        }
    }

}
